'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { ChainType, ChainConfig, getChainConfig, DEFAULT_CHAIN, isValidChain } from '@/config/chains';

interface ChainContextType {
  currentChain: ChainType;
  chainConfig: ChainConfig;
  switchChain: (chainId: ChainType) => void;
  isMainnet: boolean;
  isTestnet: boolean;
}

const ChainContext = createContext<ChainContextType | undefined>(undefined);

interface ChainProviderProps {
  children: ReactNode;
}

export const ChainProvider: React.FC<ChainProviderProps> = ({ children }) => {
  const [currentChain, setCurrentChain] = useState<ChainType>(DEFAULT_CHAIN);

  // Load saved chain from localStorage
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const savedChain = localStorage.getItem('dtv_admin_chain');
      if (savedChain && isValidChain(savedChain)) {
        setCurrentChain(savedChain);
      }
    }
  }, []);

  // Save chain to localStorage when it changes
  useEffect(() => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('dtv_admin_chain', currentChain);
    }
  }, [currentChain]);

  const switchChain = (chainId: ChainType) => {
    setCurrentChain(chainId);
  };

  const chainConfig = getChainConfig(currentChain);

  const value: ChainContextType = {
    currentChain,
    chainConfig,
    switchChain,
    isMainnet: currentChain === 'mainnet',
    isTestnet: currentChain === 'testnet',
  };

  return <ChainContext.Provider value={value}>{children}</ChainContext.Provider>;
};

export const useChain = (): ChainContextType => {
  const context = useContext(ChainContext);
  if (context === undefined) {
    throw new Error('useChain must be used within a ChainProvider');
  }
  return context;
};